/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.io.xfer;

import java.util.HashMap;
import java.util.LinkedList;

import dijjer.AbstractFactory;
import dijjer.io.comm.AbstractPeer;
import dijjer.io.comm.AbstractUdpSocketManager;
import dijjer.io.comm.DMT;
import dijjer.io.comm.Message;
import dijjer.io.comm.MessageFilter;
import dijjer.io.comm.RetrievalException;
import dijjer.util.BitArray;
import dijjer.util.Buffer;
import dijjer.util.logging.Logger;

/**
 * @author ian
 * 
 * To change the template for this generated type comment go to Window - Preferences - Java - Code Generation - Code and
 * Comments
 */
public class BlockReceiver {

	public static final int RECEIPT_TIMEOUT = 5000;
	public static final int INITIAL_RECEIPT_TIMEOUT = 15000;
	// TODO: This should be proportional to the calculated round-trip-time, not a constant
	public static final int MAX_ROUND_TRIP_TIME = RECEIPT_TIMEOUT;
	public static final int MAX_CONSECUTIVE_MISSING_PACKET_REPORTS = 2;
	public static final int MAX_SEND_INTERVAL = 500;
	PartiallyReceivedBlock _prb;
	AbstractPeer _sender;
	int _uid;
	AbstractUdpSocketManager _usm;
	/** packet : Integer -> reportTime : Long * */
	HashMap _recentlyReportedMissingPackets = new HashMap();

	public BlockReceiver(AbstractUdpSocketManager usm, AbstractPeer sender, int uid, PartiallyReceivedBlock prb) {
		_sender = sender;
		_prb = prb;
		_uid = uid;
		_usm = usm;
	}

	public byte[] receive() throws RetrievalException {
		int consecutiveMissingPacketReports = 0;
		MessageFilter f = MessageFilter.create(INITIAL_RECEIPT_TIMEOUT, DMT.packetTransmit)
						  .setField(DMT.UID, _uid)
						  .addType(DMT.allSent)
						  .addType(DMT.sendAborted);
		while (!_prb.allReceived()) {
			Message m1 = _usm.waitFor(f);
			// Get ready for the next packet
			f = MessageFilter.create(RECEIPT_TIMEOUT, DMT.packetTransmit)
				.setField(DMT.UID, _uid)
				.addType(DMT.allSent)
				.addType(DMT.sendAborted);
			// The faster we finish the rest of this loop the better!
			if ((m1 != null) && (m1.getSpec().equals(DMT.packetTransmit))) {
				consecutiveMissingPacketReports = 0;
				// packetTransmit received
				int packetNo = m1.getInt(DMT.PACKET_NO);
				BitArray sent = (BitArray) m1.getObject(DMT.SENT);
				Buffer data = (Buffer) m1.getObject(DMT.DATA);
				_prb.addPacket(packetNo, data);
				// Remove it from rrmp if its in there
				_recentlyReportedMissingPackets.remove(new Integer(packetNo));
				// Skip checks except for 1 out of 16 packets until we get to the end
				if ((_prb.numReceived() < (_prb.getNumPackets() - 16))
					&& (packetNo % 16 != 0))
					continue;
				// Check that we have what the sender thinks we have
				LinkedList missing = new LinkedList();
				for (int x = 0; x < sent.getSize(); x++) {
					if (sent.bitAt(x) && !_prb.isReceived(x)) {
						// Sender thinks we have a block which we don't, but have we already
						// re-requested it recently?
						Long resendTime = (Long) _recentlyReportedMissingPackets.get(new Integer(x));
						if ((resendTime == null) || (System.currentTimeMillis() > resendTime.longValue())) {
							// Make a note of the earliest time we should resend this, 
							// based on the number of other packets we are already waiting for
							long resendWait = System.currentTimeMillis()
									+ (10*MAX_ROUND_TRIP_TIME + (_recentlyReportedMissingPackets.size() * MAX_SEND_INTERVAL));
							_recentlyReportedMissingPackets.put(new Integer(x), (new Long(resendWait)));
							missing.add(new Integer(x));
						}
					}
				}
				if (missing.size() > 0) {
					Message mn = DMT.createMissingPacketNotification(_uid, missing);
					_usm.send(_sender, mn);
					consecutiveMissingPacketReports++;
					if (missing.size() > 50) {
						Logger.warning("Excessive packet loss : " + mn);
					}
				}
				continue;
			}
			if ((m1 != null) && m1.getSpec().equals(DMT.sendAborted)) {
				_prb.abort(m1.getInt(DMT.REASON), m1.getString(DMT.DESCRIPTION));
				throw new RetrievalException(m1.getInt(DMT.REASON), m1.getString(DMT.DESCRIPTION));
			}
			if ((m1 == null) || (m1.getSpec().equals(DMT.allSent))) {
				if (consecutiveMissingPacketReports >= MAX_CONSECUTIVE_MISSING_PACKET_REPORTS) {
					_prb.abort(RetrievalException.SENDER_DIED, "Sender unresponsive to resend requests");
					LinkedList rem = new LinkedList();
					rem.add(_sender);
					// TODO: This is a stupid work around for BlockTransferTest and needs to be fixed
					if (AbstractFactory.getFactory().getRoutingTable() != null)
					AbstractFactory.getFactory().getRoutingTable().removePeers(rem, "Failed to send data after acking request");
					throw new RetrievalException(RetrievalException.SENDER_DIED,
							"Sender unresponsive to resend requests");
				}
				LinkedList missing = new LinkedList();
				for (int x = 0; x < _prb.getNumPackets(); x++) {
					if (!_prb.isReceived(x)) {
						missing.addFirst(new Integer(x));
					}
				}
				Message mn = DMT.createMissingPacketNotification(_uid, missing);
				_usm.send(_sender, mn);
				consecutiveMissingPacketReports++;
				if (missing.size() > 50) {
					Logger.warning("Sending large missingPacketNotification to " + _sender
							+ " due to packet receiver timeout after " + RECEIPT_TIMEOUT + "ms having received "
							+ _prb.numReceived());
				}
			}
		}
		_usm.send(_sender, DMT.createAllReceived(_uid));
		return _prb.getBlock();
	}
}
